<template>
  <div class="report-wrapper">
    <px-tabs v-model="activeTab" class="equipment-tabs" style="padding-left: 24px; background: white" @tab-change="activeTabChange">
      <px-tab-pane v-for="(item, index) in tabPaneList" :key="index" :name="item.name">
        <template #label>
          <p class="pane-bottom">{{ item.label }}</p>
          <p class="pane-line" />
        </template>
      </px-tab-pane>
    </px-tabs>
    <div class="search-wrapper">
      <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" inline label-width="90px">
        <px-row :gutter="16" style="padding-right: 10px">
          <px-col :span="5">
            <px-form-item label="时间" prop="timeRange">
              <px-date-picker
                v-model="queryParams.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="请选择开始时间"
                end-placeholder="请选择结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </px-form-item>
          </px-col>
          <px-col v-if="activeTab == 'detail'" :span="4">
            <px-form-item label="高风险作业" prop="risk">
              <px-select v-model="queryParams.risk" placeholder="请选择" clearable filterable>
                <px-option v-for="item in riskList" :key="item" :label="item" :value="item" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col v-if="activeTab == 'detail'" :span="3">
            <px-form-item label="负责人" prop="owner">
              <px-select v-model="queryParams.owner" clearable filterable placeholder="请选择">
                <px-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col v-if="activeTab == 'detail'" :span="3">
            <px-form-item label="非Routine" prop="notRoutine">
              <px-select v-model="queryParams.notRoutine" placeholder="请选择" clearable filterable>
                <px-option v-for="item in routineList" :key="item" :label="item" :value="item" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col v-if="activeTab == 'detail'" :span="3">
            <px-form-item label="类型" prop="type">
              <px-select v-model="queryParams.type" placeholder="请选择" clearable filterable>
                <px-option v-for="item in typeList" :key="item.itemName" :label="item.itemName" :value="item.itemName" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col v-if="activeTab == 'detail'" :span="4">
            <px-form-item label="系统" prop="system">
              <px-select v-model="queryParams.system" placeholder="请选择" clearable filterable>
                <px-option v-for="item in systemList" :key="item.itemName" :label="item.itemName" :value="item.itemName" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="2">
            <px-form-item style="width: 130px" class="option-item">
              <px-button type="primary" @click="searchAction">查询</px-button>
              <px-button v-has="'WATER_REPORT_WORK_EXPORT'" type="primary" plain @click="exportAction">导出</px-button>
              <!-- <px-button @click="resetQuery">重置</px-button> -->
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
    </div>
    <div v-if="activeTab == 'summary'" class="summary-wrapper">
      <div style="position: relative; height: 280px; margin: 16px 0; overflow-y: hidden; background: #fff">
        <iframe id="reportFrameS" :src="fvsUrl" width="100%" height="280" frameborder="0" />
      </div>
      <div class="frame-wrapper">
        <iframe id="reportFrame1" :src="templateUrlS" width="100%" height="100%" frameborder="0" />
      </div>
    </div>
    <div v-if="activeTab == 'detail'" class="detail-wrapper">
      <div class="frame-wrapper">
        <iframe id="reportFrame2" :src="templateUrl" width="100%" height="100%" frameborder="0" />
      </div>
    </div>

    <ReTeleport>
      <div v-if="activeTab == 'summary'" class="op-btns footer-btns">
        <div class="right"><px-button v-has="'WATER_REPORT_WORK_SUMMARY_SUBMIT'" type="primary" @click="submitAction">提交</px-button></div>
      </div>
      <div v-if="activeTab == 'detail'" class="op-btns footer-btns">
        <div class="right"><px-button v-has="'WATER_REPORT_WORK_DETAIL_SUBMIT'" type="primary" @click="submitAction">提交</px-button></div>
      </div>
    </ReTeleport>
  </div>
</template>

<script setup lang="ts">
import { queryChildByTypeCodeAndItemValue } from "@/api/common";
import { onMounted, reactive, toRefs, ref, computed, nextTick } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { getEmployeeIdAndNameByClassCode } from "@/utils/pengxi";
import { useRouter, useRoute } from "vue-router";
import { useNav } from "@/layout/hooks/useNav";
import dayjs from "dayjs";
import { getToken } from "@/utils/auth";
import ReTeleport from "@/components/ReTeleport";

defineOptions({
  name: "WATER_REPORT_WORK"
});
const { VITE_FANRUAN_BASE_URL } = import.meta.env;
const { username } = useNav();
const router = useRouter();
const route = useRoute();

const templateUrl = ref();
const templateUrlS = ref();
const fvsUrl = ref();
const activeTab = ref("summary");
const tabPaneList = [
  {
    label: "汇总",
    name: "summary"
  },
  {
    label: "明细",
    name: "detail"
  }
];

const riskList = ref(["动火作业", "高处作业", "开挖作业", "有限空间作业", "特种设备作业", "消防系统中断作业", "危险性管路裁接作业"]);
const routineList = ref(["Y", "N"]);
const systemList = ref([]);
const typeList = ref([]);
const userList = ref([]);
const queryParams = reactive({
  timeRange: "",
  risk: "",
  owner: "",
  notRoutine: "",
  type: "",
  system: ""
});
const addLineAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().clickAddLineButton", "*");
};
const deleteLineAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().clickDeleteLineButton", "*");
};

const submitAction = () => {
  if (activeTab.value == "summary") {
    document.getElementById("reportFrame1").contentWindow.postMessage("_g().verifyAndWriteReport()", "*");
  } else {
    document.getElementById("reportFrame2").contentWindow.postMessage("_g().verifyAndWriteReport()", "*");
  }
};
// importExcel_Clean清空导入
// importExcel_Append 增量导入
// importExcel_Cover 覆盖导入
const importAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().importExcel_Cover()", "*");
};
const exportAction = () => {
  let startDate = queryParams?.timeRange?.[0] || "";
  let endDate = queryParams?.timeRange?.[1] || "";
  if (activeTab.value == "summary") {
    let tpName = encodeURIComponent(encodeURIComponent("reportCenter/water/每日重要工作汇总.cpt"));
    let url = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=${tpName}&user=${username.value}&op=write&facCode=${localStorage.getItem("facCode") || ""}&format=excel&extype=simple&__filename__=每日重要工作汇总${startDate}_${endDate}_${dayjs().format("YYYYMMDDHHmmss")}`;
    window.location.href = url;
    console.log(url);
    // document.getElementById("reportFrame1").contentWindow.postMessage("_g().exportReportToExcel('simple')", "*");
  } else {
    let tpName = encodeURIComponent(encodeURIComponent("reportCenter/water/每日重要工作.cpt"));
    let baseUrl = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=${tpName}&user=${username.value}&__pi__=false&op=write&facCode=${localStorage.getItem("facCode") || ""}`;
    if (startDate && endDate) {
      baseUrl = `${baseUrl}&startDate=${startDate}&endDate=${endDate}`;
    }
    if (queryParams.risk) {
      baseUrl = `${baseUrl}&risk=${queryParams.risk}`;
    }
    if (queryParams.owner) {
      baseUrl = `${baseUrl}&owner=${queryParams.owner}`;
    }
    if (queryParams.notRoutine) {
      baseUrl = `${baseUrl}&notRoutine=${queryParams.notRoutine}`;
    }
    if (queryParams.type) {
      baseUrl = `${baseUrl}&type=${queryParams.type}`;
    }
    if (queryParams.system) {
      baseUrl = `${baseUrl}&system=${queryParams.system}`;
    }
    let atoken = getToken().accessToken || "";
    baseUrl = `${baseUrl}&token=${atoken}&apiHost=${window.location.protocol}//${window.location.hostname}&format=excel&extype=simple&__filename__=每日重要工作${startDate}_${endDate}_${dayjs().format("YYYYMMDDHHmmss")}`;
    window.location.href = baseUrl;
    console.log(baseUrl);
    // document.getElementById("reportFrame2").contentWindow.postMessage("_g().exportReportToExcel('simple')", "*");
  }
};

const printAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage(`_g().noClientPrint(true,true)`, "*");
};

const getUrl = () => {
  if (activeTab.value == "summary") {
    let tpName = encodeURIComponent(encodeURIComponent("reportCenter/water/每日重要工作汇总.cpt"));
    let baseUrl = `${window.location.protocol}//${window.location.hostname}:8443/webroot/decision/view/report?viewlet=${tpName}&user=${username.value}&__pi__=false&op=write&facCode=${localStorage.getItem("facCode") || ""}`;
    let startDate = queryParams?.timeRange?.[0] || "";
    let endDate = queryParams?.timeRange?.[1] || "";
    if (startDate && endDate) {
      baseUrl = `${baseUrl}&startDate=${startDate}&endDate=${endDate}`;
    }
    let atoken = getToken().accessToken || "";
    baseUrl = `${baseUrl}&token=${atoken}&apiHost=${window.location.protocol}//${window.location.hostname}&ts=${new Date().getTime()}`;
    templateUrlS.value = baseUrl;
    let baseUrlS = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/duchamp?viewlet=reportCenter%252Fwater%252FdailyworkSummary.fvs&user=${username.value}&facCode=${localStorage.getItem("facCode") || ""}&ts=${new Date().getTime()}`;
    if (startDate && endDate) {
      baseUrlS = `${baseUrlS}&startDate=${startDate}&endDate=${endDate}`;
    }
    fvsUrl.value = `${baseUrlS}`;
  } else {
    let tpName = encodeURIComponent(encodeURIComponent("reportCenter/water/每日重要工作.cpt"));
    let baseUrl = `${window.location.protocol}//${window.location.hostname}:8443/webroot/decision/view/report?viewlet=${tpName}&user=${username.value}&__pi__=false&op=write&facCode=${localStorage.getItem("facCode") || ""}`;
    let startDate = queryParams?.timeRange?.[0] || "";
    let endDate = queryParams?.timeRange?.[1] || "";
    if (startDate && endDate) {
      baseUrl = `${baseUrl}&startDate=${startDate}&endDate=${endDate}`;
    }
    if (queryParams.risk) {
      baseUrl = `${baseUrl}&risk=${queryParams.risk}`;
    }
    if (queryParams.owner) {
      baseUrl = `${baseUrl}&owner=${queryParams.owner}`;
    }
    if (queryParams.notRoutine) {
      baseUrl = `${baseUrl}&notRoutine=${queryParams.notRoutine}`;
    }
    if (queryParams.type) {
      baseUrl = `${baseUrl}&type=${queryParams.type}`;
    }
    if (queryParams.system) {
      baseUrl = `${baseUrl}&system=${queryParams.system}`;
    }
    let atoken = getToken().accessToken || "";
    baseUrl = `${baseUrl}&token=${atoken}&apiHost=${window.location.protocol}//${window.location.hostname}&ts=${new Date().getTime()}`;
    templateUrl.value = baseUrl;
  }
};
const queryUserList = async () => {
  userList.value = await getEmployeeIdAndNameByClassCode(["WATER"]);
};
const getSystemList = async () => {
  systemList.value = await queryChildByTypeCodeAndItemValue({
    typeCode: "WTTS_DAILY_JOB",
    value: "WDJ_SYSTEM"
  });
};
const getTypeList = async () => {
  typeList.value = await queryChildByTypeCodeAndItemValue({
    typeCode: "WTTS_DAILY_JOB",
    value: "WDJ_TYPE"
  });
};
const activeTabChange = () => {
  console.log("activeTab:", activeTab.value);
  queryParams.timeRange = [dayjs().format("YYYY-MM-DD"), dayjs().add(1, "day").format("YYYY-MM-DD")];
  if (activeTab.value == "detail") {
    queryParams.timeRange = [dayjs().subtract(7, "day").format("YYYY-MM-DD"), dayjs().add(30, "day").format("YYYY-MM-DD")];
  }
  getUrl();
};
onMounted(() => {
  let ym = new Date();

  // 获取当前月份第一天
  // let firstDayOfMonth = dayjs(ym).subtract(1, "day").format("YYYY-MM-DD");
  let firstDayOfMonth = dayjs().format("YYYY-MM-DD");
  // 获取当前月份最后一天
  // let lastDayOfMonth = dayjs(ym).format("YYYY-MM-DD");
  let lastDayOfMonth = dayjs().add(1, "day").format("YYYY-MM-DD");
  if (route.query.date) {
    firstDayOfMonth = route.query.date;
    lastDayOfMonth = route.query.date;
  }
  queryParams.timeRange = [firstDayOfMonth, lastDayOfMonth];
  getUrl();
  queryUserList();
  getSystemList();
  getTypeList();
  window.addEventListener("message", function (event) {
    console.log(event);
    let o = `${window.location.protocol}//${window.location.hostname}:8443`;
    if (event.origin !== o) return;
    let submitSuccess = JSON.parse(event.data)?.submitSuccess;
    if (submitSuccess == 1) {
      fvsUrl.value = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/duchamp?viewlet=reportCenter%252Fwater%252FdailyworkSummary.fvs&facCode=${localStorage.getItem("facCode") || ""}&ts=${new Date().getTime()}`;
    }
  });
});

const searchAction = () => {
  getUrl();
};
</script>
<style scoped lang="scss">
:deep(.custom-form-ui .px-form-item) {
  width: 100%;
  // margin-bottom: 0;

  .px-input {
    width: 100%;
  }

  .px-select {
    width: 100%;
  }
}

.report-wrapper {
  overflow: hidden;
  // background: #fff;
  border-radius: 4px;
}

.search-wrapper {
  padding: 8px 16px 0;
  background: #fff;
  border-radius: 4px;
}

.summary-wrapper {
  .frame-wrapper {
    position: relative;
    height: calc(100vh - 606px);
    padding: 16px;
    overflow-y: hidden;
    background: #fff;
    border-radius: 4px;
  }
}

.detail-wrapper {
  .frame-wrapper {
    position: relative;
    height: calc(100vh - 310px);
    padding: 16px;
    margin-top: 16px;
    overflow-y: hidden;
    background: #fff;
    border-radius: 4px;
  }
}

.op-btns {
  display: flex;
  padding: 16px 0;
  background-color: #fff;

  .left {
    flex: 1;
    text-align: left;
  }

  .center {
    flex: 1;
    text-align: center;
  }

  .right {
    flex: 1;
    text-align: right;
  }
}

.footer-btns {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 100%;
  padding: 16px;
}
</style>
